package com.hanlin.backend.config.filter;

import cn.hutool.core.util.StrUtil;
import com.hanlin.backend.common.error.ErrorCodeEnum;
import com.hanlin.backend.common.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述：jwt拦截器
 *
 * @author:hl.yuan
 * @date:2020-12-27
 */
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        SystemProperties properties = SpringContextUtil.getBean(SystemProperties.class);
        String[] anonUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(), ",");

        String requestURI = ((HttpServletRequest) request).getRequestURI();

        boolean match = false;
        for (String u : anonUrl) {
            if (pathMatcher.match(u, httpServletRequest.getRequestURI())) {
                match = true;
            }
        }
        if (match) {
            log.info("接口{}，无需认证，直接通过", requestURI);
            return true;
        }
        if (isLoginAttempt(request, response)) {
            boolean is = executeLogin(request, response);
            if (is) {
                log.info("接口{}，token认证通过", requestURI);
            } else {
                log.info("接口{}，token认证不通过，拦截请求，跳转到/401 请求下", requestURI);
                this.urlToErrorController(request, response, "401", ErrorCodeEnum.No_TOKEN.getDesc());
            }
        } else {
            // springboot的全局异常无法捕获filter主动抛出去的异常，故这里直接把filter的异常给重新转发请求处理！
            log.info("接口{}，无token，拦截请求，跳转到/401 请求下", requestURI);
            this.urlToErrorController(request, response, "401", ErrorCodeEnum.No_TOKEN.getDesc());
        }
        return false;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader(JwtUtil.TOKEN);
        return token != null;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(JwtUtil.TOKEN);
        // 拿到token后，需要在根据token信息解析出姓名
        String username = JwtUtil.getUsername(token);
        RedisUtil redisUtil = SpringContextUtil.getBean(RedisUtil.class);
        String tokenRedis = (String) redisUtil.get("user_" + username);
        if (!StrUtil.isBlank(tokenRedis)) {
            try {
                JwtToken jwtToken = new JwtToken(token);
                getSubject(request, response).login(jwtToken);
            } catch (Exception e) {
                log.error("认证错误", e);
                return false;
            }
            // 设置redis过期时间
            redisUtil.expire("user_" + username, SpringContextUtil.getBean(SystemProperties.class).getJwtTimeOut());
            return true;
        }
        log.error("redis没有存储{}的会话token", username);
        return false;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个 option请求，这里我们给 option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * url请求跳转到errorController
     *
     * @param request
     * @param response
     * @param errorCode
     * @param desc
     */
    private void urlToErrorController(ServletRequest request, ServletResponse response, String errorCode, String desc) {
        try {
            // 将错误信息封装在request中
            request.setAttribute("errorMessage", desc);
            // 请求转发
            request.getRequestDispatcher("/error/" + errorCode).forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
